//
//  EditWeightEntryViewController.m
//  IWeighMyself
//
//  Created by Francisco Gindre on 9/8/10.
//  Copyright 2010 Apps Crafter. All rights reserved.
//

#import "EditWeightEntryViewController.h"
#import "DatePickerViewController.h"
#import "WeightScalePickerViewController.h"
#import "DatabaseUtils.h"
#import "WeightListViewController.h"
@implementation EditWeightEntryViewController
@synthesize sentCell;
@synthesize weightList;



#pragma mark -
#pragma mark constants

#define TOTAL_SECTIONS 3
#define WEIGHT_SECTION 0
#define DATE_SECTION 1
#define SENT_SECTION 2


#pragma mark -
#pragma mark constructor

-(id)initWithWeight:(Weight*)aWeight theWeightList:(WeightListViewController*)parentView{
	
	self = [[EditWeightEntryViewController alloc] initWithNibName:@"EditWeightEntryViewController" bundle:nil];
	
	
	
	if (self) {
		
		self.currentEntry = [aWeight retain];
		
		self.weightList = [parentView retain];
		
	}
	
	return self;
}

#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
   //	[super viewDidLoad];
	
	
	
	
	
	//Set the localized Title for the window
	super.title = NSLocalizedString(@"EditWeightEntryTitle",@"");
	
	
	super.sectionTitles = [NSArray arrayWithObjects:NSLocalizedString(@"LogNewWeightViewWeight",@""),
						  NSLocalizedString(@"LogNewWeightViewDate",@""),
						  NSLocalizedString(@"EditWeightEntryTitle",@""),nil];
	
	
	/*
	 get last entry, if nil, then do defaults
	 */
	self.appDelegate = [[UIApplication sharedApplication] delegate];
	
	NSLog(@"currentEntry: %@", [self.currentEntry weightToString]);
	
    /*
	 set save button
	 */
	self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle: NSLocalizedString(@"SaveButtonTitle",@"")
																			   style:UIBarButtonSystemItemDone target:self action:@selector(saveChanges:)];
	

	
}


/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return [sectionTitles count];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return 1;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
	
	/** 
	 * Since the cells are not homogeneus, specify creation depending on index path
	 */
    static NSString *CellIdentifier = @"Cell";
    NSString *base;
	NSString *text;
    UITableViewCell *cell;     
    // Configure the cell...
	
	switch (indexPath.section) {
		case WEIGHT_SECTION:
			cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
			if (cell == nil) {
				cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
			}
			
			if ([self.appDelegate isKilosWeightSelectedUnit]) {
				
				base = [NSString stringWithFormat:@"%.1f ",[self.currentEntry.weightInKilos floatValue]];
				//NSLog(@"base string: %@",base);
				text = [base stringByAppendingString:NSLocalizedString(@"WeightUnitKilos",@"")];
				
				
				
			} else {
				base = [NSString stringWithFormat:@"%.1f ",[self.currentEntry.weightInPounds floatValue]];
				//NSLog(@"base string: %@",base);
				text = [base stringByAppendingString:NSLocalizedString(@"WeightUnitPounds",@"")];
				
			}
			
			[cell.textLabel setText:text];
			cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

			
			break;
		case DATE_SECTION:
			cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
			if (cell == nil) {
				cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
			}
			// set text
			text = [NSDateFormatter localizedStringFromDate:self.currentEntry.dateLogged
												  dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterNoStyle];
			NSLog(@"text date:  %@",text);
			[cell.textLabel setText:text];
			cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

			break;
			
		case SENT_SECTION:
			if (self.sentCell == nil)
				cell = [self tableView: tableView createSentCell:indexPath];
			
			//set value that matches current entry
			[self.sentCell.sentSwitch setOn:self.currentEntry.wasSent];
			//return the sentCell
			return self.sentCell;
			break;
			
			
	}
	// return the normal cell
	return cell;
}


- (WeightSentCell *)tableView:(UITableView *)tableView createSentCell:(NSIndexPath *)indexPath {

	static NSString *identifier = @"SentCellIdentifier";
	
	WeightSentCell *cell  = (WeightSentCell*) [tableView dequeueReusableCellWithIdentifier:identifier];
	
	if (cell == nil ) {
		
		[[NSBundle mainBundle] loadNibNamed:@"WeightSentCell" owner:self options:nil];
		
		cell  = self.sentCell;
	
	}
	
	return cell;
	
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	/*
	 <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
	 [self.navigationController pushViewController:detailViewController animated:YES];
	 [detailViewController release];
	 */
	WeightScalePickerViewController *weightPicker;
	switch (indexPath.section) {
		case WEIGHT_SECTION:
			/*
			 show the weight selector
			 */
			weightPicker = [[WeightScalePickerViewController alloc] initWithWeightAndParentView:currentEntry parentView:self];
			
			[self.navigationController pushViewController:weightPicker animated:YES];
			[weightPicker release];
			break;
			
		case DATE_SECTION:
			/*
			 
			 show Date picker
			 */
			
			[self.navigationController pushViewController:[[DatePickerViewController alloc]initWithParentView:self aDate:self.currentEntry.dateLogged] animated:YES];
			break;
			
	}
	
}

#pragma mark -
#pragma mark custom actions

-(IBAction) switchChanged:(id)sender {
	NSLog(@"Switch changed to %d",([sentCell.sentSwitch isOn])?1:0);
	
	self.currentEntry.wasSent = [sentCell.sentSwitch isOn];
}
-(void) saveChanges:(id)sender {
	NSLog(@"savechanges");
	
	[DatabaseUtils updateEntryFromDatabase:self.appDelegate.databasePath weight:self.currentEntry fromTable:@"weight"];
	
	[weightList userEditedValue];
	
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end

